package com.im.netty.group;


import com.alibaba.fastjson.JSON;
import com.im.mapper.user.UserMapper;
import com.im.model.*;
import com.im.service.user.UserService;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.net.URLDecoder;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
public class ChannelGroup {

    @Autowired
    UserService userService;
    @Autowired
    UserMapper userMapper;

    ConcurrentHashMap<String,Channel> personMap = new ConcurrentHashMap(256);


    ConcurrentHashMap<String,Map<String,Channel>> groupMap = new ConcurrentHashMap<>(256);
    public void add(String name,Channel channel){
        personMap.put(name,channel);
    }

    public void remove(String name,Channel channel){
        personMap.remove(name);
    }

    public synchronized void registerUser(String id, Channel channel) {
        User userInfo = userMapper.getUserInfo(id);
        personMap.put(userInfo.getId(),channel);
        //查询用户群组
        List<Groups> groups = userMapper.getGroups(id);
        for (Groups group : groups) {
            if (groupMap.containsKey(group.getId())){
                groupMap.get(group.getId()).put(id,channel);
            }else {
                Map<String, Channel> map = new HashMap<>();
                map.put(id,channel);
                groupMap.put(group.getId(),map);
            }
        }
        SystemMsg systemMsg = new SystemMsg();
        systemMsg.setContent("服务器连接成功");
        systemMsg.setId(UUID.randomUUID().toString().replaceAll("-",""));
        channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(systemMsg)));
    }

    public void handlerPrivateChat(SocketRequest socketRequest, Channel channel) {
        //私聊
        SimpleMsg simpleMsg = new SimpleMsg();
        simpleMsg.setContent(socketRequest.getMine().getContent());
        simpleMsg.setAvatar(socketRequest.getMine().getAvatar());
//        simpleMsg.setCid();
        simpleMsg.setFromid(socketRequest.getMine().getId());
        simpleMsg.setId(socketRequest.getMine().getId());
        simpleMsg.setUsername(socketRequest.getMine().getUsername());
        simpleMsg.setType(socketRequest.getTo().getType());
        Channel channel1 = personMap.get(socketRequest.getTo().getId());
        if (channel1!=null){
            channel1.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(simpleMsg)));
        }else {
            log.info("send message to {} is not online you can execute other operation example off-line log",socketRequest.getTo().getUsername());
        }

    }

    public void handlerGroupsChat(SocketRequest socketRequest, Channel channel) {
        //群聊
        SimpleMsg simpleMsg = new SimpleMsg();
        simpleMsg.setType(socketRequest.getTo().getType());
        simpleMsg.setId(socketRequest.getTo().getId());
        simpleMsg.setUsername(socketRequest.getMine().getUsername());
        simpleMsg.setFromid(socketRequest.getMine().getId());
        simpleMsg.setAvatar(socketRequest.getMine().getAvatar());
        simpleMsg.setContent(socketRequest.getMine().getContent());
        Map<String, Channel> map = groupMap.get(socketRequest.getTo().getId());
        TextWebSocketFrame textWebSocketFrame = new TextWebSocketFrame(JSON.toJSONString(simpleMsg));
        Set<Map.Entry<String, Channel>> entries = map.entrySet();
        for (Map.Entry<String, Channel> entry : entries) {
            Channel value = entry.getValue();
            if (value!=channel){
                TextWebSocketFrame copy = textWebSocketFrame.copy();
                log.info("发送群聊消息");
                value.writeAndFlush(copy);
            }
        }

    }

    //好友申请
    public void sendMsgForAddFriend(String toId) {

        Channel channel = personMap.get(toId);
        if (null!=channel){
            if (channel.isOpen()){
                //发送好友申请
                SystemMsg systemMsg = new SystemMsg();
                systemMsg.setContent("好友申请");
                systemMsg.setId("0");
                systemMsg.setType("addFriend");
                systemMsg.setTimestamp(System.currentTimeMillis());
                channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(systemMsg)));
                return;
            }
        }
        log.info("好友不在线，添加好友申请发送失败");
    }

    public void agree(String uid, String from,String userLogFrom) {
        Channel channel = personMap.get(uid);
        if (channel!=null && channel.isOpen()){
            SystemMsg systemMsg = new SystemMsg();
            systemMsg.setContent("同意申请");
            systemMsg.setId("0");
            systemMsg.setType("agree");
            systemMsg.setTimestamp(System.currentTimeMillis());
            systemMsg.setUser(userMapper.getUserInfo(from));
            systemMsg.setGroupId(userLogFrom);
            channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(systemMsg)));
            return;
        }
        log.info("好友不在线，同意好友申请发送失败");
    }
}
